package webs

import (
	"bytes"
	"io/ioutil"
	"strings"

	"gitee.com/xuender/oils/base"
	"gitee.com/xuender/oils/logs"
	"github.com/kataras/iris/v12"
	"github.com/lithammer/shortuuid"
	"gopkg.in/yaml.v3"
)

// Handler 句柄.
type Handler struct {
	Method string // GET POST PUT DELETE
	Path   string // 路径
	File   string // 文件
	Type   string // Binary,Text,HTML,JSON,JSONP,XML
	data   []byte //
}

// Handler 句柄.
func (h Handler) Handler(ctx iris.Context) {
	if h.data == nil {
		var err error
		h.data, err = ioutil.ReadFile(h.File)

		if err != nil {
			logs.Errorf("文件错误:%s,%v\n", h.File, err)
			panic(err)
		}

		h.data = bytes.ReplaceAll(h.data, []byte("UUID"), []byte(shortuuid.New()))
	}

	if h.data == nil {
		return
	}
	// fmt.Printf("%s: %s -> %s", h.Method, h.Path, h.File)
	if strings.EqualFold(h.Type, "Json") {
		ctx.Header("Content-Type", "application/json")
		base.Panic1(ctx.Write(h.data))

		return
	}

	if strings.EqualFold(h.Type, "Text") {
		base.Panic1(ctx.Text(string(h.data)))

		return
	}

	if strings.EqualFold(h.Type, "Binary") {
		base.Panic1(ctx.Binary(h.data))

		return
	}
}

// Load 加载.
func Load(file string) (hs []Handler, err error) {
	var data []byte

	if data, err = ioutil.ReadFile(file); err != nil {
		return
	}

	err = yaml.Unmarshal(data, &hs)

	return
}
